package com.liu.auth.interceptor;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;

/**
 * 因为购物车模块通过feign调用此模块时，
 * feign会在底层发送一个新的请求，新的请求中就会丢失原来的请求中的请求头，从而导致在购物车模块中拿不到请求头中的cookie
 * 所以要重写新的请求，并将原来的请求头中的数据复制到新的请求头中。
 */
@Component
public class FeignHeadInterceptor implements RequestInterceptor {
    @Override
    public void apply(RequestTemplate requestTemplate) {

        // 1.获取HttpServletRequset对象
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();

        // 2.从req对象中获取请你头
        Enumeration<String> headerNames = request.getHeaderNames();

        // 3.遍历，将原来的请求头中的数据复制到新的请求头中
        while (headerNames.hasMoreElements()) {
            String key = headerNames.nextElement();
            String value = request.getHeader(key);

            // 3.全部放到新的请求头中
            requestTemplate.header(key, value);
        }
    }
}
